<?php
/**
 *@author Connor <caokang@foxmail.com>
 *@todo
 *@link www.zeevin.com
 */
class PmController extends BaseController{

	public function actionInbox(){
		$p['s']=$_GET['s']?:Pm::PM_STATUS_OK;
		$p['isread']=$_GET['isread'];
		$p['tid']=Yii::app()->user->id;
		$p['del_status_sec'] = Pm::PM_DEL_NORMAL;

		$rs = Pm::getList($p);
		$this->render('inbox',array('data'=>$rs));
	}

	public function actionOutbox(){
		$p['s']=$_GET['s']?:Pm::PM_STATUS_OK;
		$p['isread']=$_GET['isread'];
		$p['fid']=Yii::app()->user->id;
		$p['del_status'] = Pm::PM_DEL_NORMAL;

		$rs = Pm::getList($p);
		// print_r($mails);
		$this->render('outbox',array('data'=>$rs));
	}

	public function actionDetail(){
		$id = $_GET['id'];
		$rs = Pm::model()->findByPk($id);
		if(!$rs){
			throw new Exception("您查找的消息不存在！", 1);
		}
		if(($rs->from_uid!=Yii::app()->user->id) && ($rs->to_uid!=Yii::app()->user->id)){
			throw new Exception("Access denied!", 1);
		}

		if($rs->is_read!=PM::PM_READ_STATUS_YES){
			$rs->is_read = PM::PM_READ_STATUS_YES;
			$rs->save();
		}

		$this->render('detail',array('rs'=>$rs));
	}

	public function actionNew(){
		$model = new Pm('create');
		$receiver = User::model()->findByPk($_GET['tid']);

		if(Yii::app()->request->isAjaxRequest){

			$msg['status']=1;
			$msg['desc']='消息发送失败';
			$model->attributes = $_POST['Pm'];
			$tid=$_POST['Pm']['to_uid'];
			$black=Black::model()->findByAttributes(array('uid'=>$tid,'bid'=>Yii::app()->user->id));//查看是否在收件人的黑名单
			// var_dump($black);exit;
			$like_tags = UserTages::getLike();//获取发信人喜欢的标签
			$hate_tags = UserTages::getHate($tid);//获取收信人排斥的标签
			$same = array_intersect($like_tags,$hate_tags);
			if($black||count($same)>0){
				$model->status=1;
			}
			if($model->save()){
				$msg['status']=0;
				$msg['desc']='消息发送成功';
			}else{
				$msg['desc']=$model->getErrors();
			}
			echo json_encode($msg);
			exit;
		}
		// var_dump($receiver);
		$this->render('new',array('model'=>$model,'receiver'=>$receiver));
	}

	public function actionDelete(){
		if(Yii::app()->request->isAjaxRequest){
			$msg['status']=1;
			$msg['desc']='操作失败';
			foreach($_POST['mids'] as $v){
				if($v)$tmp[]=$v;
			}
			$tmp = implode(',',$tmp);
			if($_POST['type']=='outbox')
				$rs = Yii::app()->db->createCommand("update pm_messages set del_status=1 where from_uid=$this->uid and id in ($tmp)");
			else
				$rs = Yii::app()->db->createCommand("update pm_messages set del_status_sec=1 where to_uid=$this->uid and id in ($tmp)");


			if($rs->execute()){
				$msg['status']=0;
				$msg['desc']='操作成功';
			}
			echo json_encode($msg);
		}
		

	}




}